/**
 * JSON 对比工具
 * 专门用于 JSON 数据的语义对比和可视化
 */

// 导入依赖
// 注意：在浏览器环境中，这些类应该通过HTML中的script标签引入

class JSONComparator {
    constructor() {
        this.currentDiffs = [];
        this.highlightManager1 = null;
        this.highlightManager2 = null;
        this.init();
    }

    init() {
        // 获取 DOM 元素
        this.editor1 = document.getElementById('jsonEditor1');
        this.editor2 = document.getElementById('jsonEditor2');
        this.error1 = document.getElementById('jsonError1');
        this.error2 = document.getElementById('jsonError2');
        this.stats1 = document.getElementById('stats1');
        this.stats2 = document.getElementById('stats2');
        this.diffSummary = document.getElementById('diffSummary');
        this.overlay1 = document.getElementById('highlightOverlay1');
        this.overlay2 = document.getElementById('highlightOverlay2');
        this.lineNumbers1 = document.getElementById('lineNumbers1');
        this.lineNumbers2 = document.getElementById('lineNumbers2');

        // 初始化高亮管理器
        this.highlightManager1 = new HighlightManager(this.editor1, this.overlay1, this.lineNumbers1);
        this.highlightManager2 = new HighlightManager(this.editor2, this.overlay2, this.lineNumbers2);

        // 设置编辑器
        this.setupEditors();

        // 绑定事件
        this.bindEvents();

        // 调试信息
        console.log('JSONComparator initialized');
        console.log('Editor1:', this.editor1);
        console.log('Overlay1:', this.overlay1);
        console.log('LineNumbers1:', this.lineNumbers1);

        // 添加动态样式以确保高亮显示
        this.addDynamicStyles();

        // 检查样式是否正确应用
        setTimeout(() => {
            this.checkHighlightStyles();
        }, 1000);
    }

    // 动态添加高亮样式
    addDynamicStyles() {
        // 检查是否已经添加过样式
        if (document.getElementById('json-comparator-dynamic-styles')) {
            return;
        }

        // 创建样式元素
        const style = document.createElement('style');
        style.id = 'json-comparator-dynamic-styles';
        style.textContent = `
            /* 重构版高亮样式 - 使用更直接的方式 */
            .diff-added {
                background-color: #d4edda !important;
                border-left: 4px solid #28a745 !important;
            }
            
            .diff-removed {
                background-color: #f8d7da !important;
                border-left: 4px solid #dc3545 !important;
            }
            
            .diff-modified {
                background-color: #fff3cd !important;
                border-left: 4px solid #ffc107 !important;
            }
            
            .highlight-overlay .diff-added {
                background-color: #d4edda !important;
                border-left: 4px solid #28a745 !important;
            }
            
            .highlight-overlay .diff-removed {
                background-color: #f8d7da !important;
                border-left: 4px solid #dc3545 !important;
            }
            
            .highlight-overlay .diff-modified {
                background-color: #fff3cd !important;
                border-left: 4px solid #ffc107 !important;
            }
        `;

        // 添加到head中
        document.head.appendChild(style);
        console.log('Dynamic styles added for JSON comparator');
    }

    // 检查高亮样式是否正确应用
    checkHighlightStyles() {
        console.log('Checking highlight styles...');

        // 检查是否有样式规则
        const sheets = document.styleSheets;
        let foundHighlightRules = false;

        for (let i = 0; i < sheets.length; i++) {
            try {
                const rules = sheets[i].cssRules || sheets[i].rules;
                for (let j = 0; j < rules.length; j++) {
                    if (rules[j].selectorText && (
                        rules[j].selectorText.includes('.diff-added') ||
                        rules[j].selectorText.includes('.diff-removed') ||
                        rules[j].selectorText.includes('.diff-modified')
                    )) {
                        console.log('Found highlight style rule:', rules[j].selectorText);
                        foundHighlightRules = true;
                    }
                }
            } catch (e) {
                console.log('Cannot access stylesheet:', e);
            }
        }

        if (!foundHighlightRules) {
            console.warn('No highlight style rules found');
        } else {
            console.log('Highlight style rules found');
        }

        // 检查元素是否正确应用样式
        if (this.overlay1 && this.overlay2) {
            console.log('Overlay1 style:', window.getComputedStyle(this.overlay1).position);
            console.log('Overlay2 style:', window.getComputedStyle(this.overlay2).position);
        }
    }

    setupEditors() {
        // 防抖的对比函数
        this.debouncedCompare = this.debounce(() => {
            this.autoCompareJSON();
        }, 500);
    }

    bindEvents() {
        // 输入事件
        this.editor1.addEventListener('input', () => {
            this.handleInput(1);
        });

        this.editor2.addEventListener('input', () => {
            this.handleInput(2);
        });

        // 粘贴事件
        this.editor1.addEventListener('paste', (e) => {
            this.handlePaste(1, e);
        });

        this.editor2.addEventListener('paste', (e) => {
            this.handlePaste(2, e);
        });

        // 同步滚动：滚动一个编辑器时，另一个也跟着滚动
        let isScrolling = false;

        this.editor1.addEventListener('scroll', () => {
            if (!isScrolling) {
                isScrolling = true;
                this.editor2.scrollTop = this.editor1.scrollTop;
                this.editor2.scrollLeft = this.editor1.scrollLeft;
                setTimeout(() => isScrolling = false, 10);
            }
        });

        this.editor2.addEventListener('scroll', () => {
            if (!isScrolling) {
                isScrolling = true;
                this.editor1.scrollTop = this.editor2.scrollTop;
                this.editor1.scrollLeft = this.editor2.scrollLeft;
                setTimeout(() => isScrolling = false, 10);
            }
        });
    }

    handleInput(editorNum) {
        // 验证 JSON
        this.validateJSON(editorNum);

        // 更新统计
        this.updateStats();

        // 触发自动对比
        this.debouncedCompare();
    }

    handlePaste(editorNum, event) {
        setTimeout(() => {
            // 自动格式化粘贴的内容
            const editor = editorNum === 1 ? this.editor1 : this.editor2;
            const text = editor.value.trim();

            if (text) {
                try {
                    // 尝试解析并格式化 JSON
                    const parsed = JSON.parse(text);
                    const formatted = JSON.stringify(parsed, null, 2);
                    editor.value = formatted;
                } catch (e) {
                    // 如果不是有效的 JSON，保持原样
                    console.log('Pasted content is not valid JSON, keeping as is');
                }
            }

            this.validateJSON(editorNum);
            this.updateStats();
            this.debouncedCompare();
        }, 0);
    }

    validateJSON(editorNum) {
        const editor = editorNum === 1 ? this.editor1 : this.editor2;
        const errorDiv = editorNum === 1 ? this.error1 : this.error2;
        const text = editor.value.trim();

        if (!text) {
            errorDiv.classList.remove('show');
            return { valid: true, data: null };
        }

        try {
            const data = JSON.parse(text);
            errorDiv.classList.remove('show');
            return { valid: true, data: data };
        } catch (e) {
            errorDiv.textContent = `JSON 格式错误: ${e.message}`;
            errorDiv.classList.add('show');
            return { valid: false, error: e.message };
        }
    }

    updateStats() {
        const text1 = this.editor1.value.trim();
        const text2 = this.editor2.value.trim();

        // 统计信息
        const lines1 = text1 ? text1.split('\n').length : 0;
        const lines2 = text2 ? text2.split('\n').length : 0;
        const chars1 = text1.length;
        const chars2 = text2.length;

        this.stats1.textContent = lines1 > 0 ? `${lines1} 行, ${chars1} 字符` : '';
        this.stats2.textContent = lines2 > 0 ? `${lines2} 行, ${chars2} 字符` : '';
    }

    autoCompareJSON() {
        const result1 = this.validateJSON(1);
        const result2 = this.validateJSON(2);

        this.currentDiffs = [];

        const text1 = this.editor1.value.trim();
        const text2 = this.editor2.value.trim();

        // 如果两边都为空
        if (!text1 && !text2) {
            this.updateDiffSummary();
            this.clearHighlights();
            return;
        }

        // 两边都有内容且都是有效 JSON 时进行对比
        if (result1.valid && result2.valid && text1 && text2) {
            this.compareJSONData(result1.data, result2.data);
        } else {
            this.clearHighlights();
        }

        this.updateDiffSummary();
    }

    compareJSONData(data1, data2) {
        // 使用深度比较检查两个对象是否完全相同
        if (JSONDiffEngine.deepEqual(data1, data2)) {
            // 如果相同，则没有差异
            this.currentDiffs = [];
        } else {
            // 计算差异
            this.currentDiffs = JSONDiffEngine.computeDiff(data1, data2);
        }

        // 调试：打印差异信息
        console.log('Computed diffs:', this.currentDiffs);

        // 如果有差异，打印详细信息
        if (this.currentDiffs.length > 0) {
            console.log('Detailed diff analysis:');
            this.currentDiffs.forEach((diff, index) => {
                console.log(`  Diff ${index + 1}:`, diff);
            });
        }

        this.highlightDifferences();
    }

    updateDiffSummary() {
        if (!this.currentDiffs.length) {
            this.diffSummary.textContent = 'JSON 完全相同';
            return;
        }

        const added = this.currentDiffs.filter(d => d.type === 'added').length;
        const removed = this.currentDiffs.filter(d => d.type === 'removed').length;
        const modified = this.currentDiffs.filter(d => d.type === 'modified').length;

        const parts = [];
        if (added > 0) parts.push(`${added} 个新增`);
        if (removed > 0) parts.push(`${removed} 个删除`);
        if (modified > 0) parts.push(`${modified} 个修改`);

        this.diffSummary.textContent = `发现差异：${parts.join(', ')}`;
    }

    highlightDifferences() {
        // 调试：打印高亮信息
        console.log('Highlighting diffs:', this.currentDiffs);
        console.log('HighlightManager1:', this.highlightManager1);
        console.log('HighlightManager2:', this.highlightManager2);

        // 更新高亮
        if (this.highlightManager1 && this.highlightManager2) {
            console.log('Applying highlights to both editors');
            this.highlightManager1.updateHighlights(this.currentDiffs, 1);
            this.highlightManager2.updateHighlights(this.currentDiffs, 2);

            // 调试：检查高亮是否正确应用
            setTimeout(() => {
                console.log('Overlay1 content length:', this.overlay1.innerHTML.length);
                console.log('Overlay2 content length:', this.overlay2.innerHTML.length);

                // 检查是否有高亮类
                const hasHighlight1 = this.overlay1.innerHTML.includes('diff-');
                const hasHighlight2 = this.overlay2.innerHTML.includes('diff-');

                console.log('Overlay1 has highlight classes:', hasHighlight1);
                console.log('Overlay2 has highlight classes:', hasHighlight2);

                if (hasHighlight1 || hasHighlight2) {
                    console.log('✓ Highlight classes found, checking if they are visible');

                    // 检查元素计算样式
                    const overlay1Style = window.getComputedStyle(this.overlay1);
                    const overlay2Style = window.getComputedStyle(this.overlay2);

                    console.log('Overlay1 computed style - position:', overlay1Style.position, 'z-index:', overlay1Style.zIndex);
                    console.log('Overlay2 computed style - position:', overlay2Style.position, 'z-index:', overlay2Style.zIndex);
                } else {
                    console.log('✗ No highlight classes found in overlays');
                }
            }, 100);
        } else {
            console.error('Highlight managers not initialized');
        }
    }

    clearHighlights() {
        if (this.highlightManager1 && this.highlightManager2) {
            this.highlightManager1.clearHighlights();
            this.highlightManager2.clearHighlights();
        }
    }

    // 防抖函数
    debounce(func, delay) {
        let timeoutId;
        return function (...args) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
    }
}

// 全局函数（供 HTML 调用）
let jsonComparator;

document.addEventListener('DOMContentLoaded', () => {
    jsonComparator = new JSONComparator();
    console.log('JSONComparator created');
});

function formatJSON(editorNum) {
    if (!jsonComparator) return;

    const editor = editorNum === 1 ? jsonComparator.editor1 : jsonComparator.editor2;
    const text = editor.value.trim();

    if (!text) return;

    try {
        const formatted = JSON.stringify(JSON.parse(text), null, 2);
        editor.value = formatted;
        jsonComparator.validateJSON(editorNum);
        jsonComparator.updateStats();
        jsonComparator.debouncedCompare();
    } catch (e) {
        // 显示错误消息
        const errorDiv = editorNum === 1 ? jsonComparator.error1 : jsonComparator.error2;
        errorDiv.textContent = `JSON 格式错误：${e.message}`;
        errorDiv.classList.add('show');
    }
}

function clearJSON(editorNum) {
    if (!jsonComparator) return;

    const editor = editorNum === 1 ? jsonComparator.editor1 : jsonComparator.editor2;
    const errorDiv = editorNum === 1 ? jsonComparator.error1 : jsonComparator.error2;

    editor.value = '';
    errorDiv.classList.remove('show');

    jsonComparator.updateStats();
    jsonComparator.debouncedCompare();
}

// 测试功能
async function runTest() {
    if (!jsonComparator) {
        console.error('JSONComparator not initialized');
        UIUtils.showToast('测试失败：JSON 对比工具未初始化', 'error');
        return;
    }

    console.log('=== 开始测试 ===');
    UIUtils.showToast('正在加载测试数据...', 'info', 2000);

    try {
        // 步骤 1: 加载测试数据
        console.log('步骤 1: 从外部文件加载测试数据');
        const [json1Response, json2Response] = await Promise.all([
            fetch('test1.json'),
            fetch('test2.json')
        ]);

        if (!json1Response.ok || !json2Response.ok) {
            throw new Error('无法加载测试文件');
        }

        const testJson1 = await json1Response.text();
        const testJson2 = await json2Response.text();

        console.log('✓ 测试数据加载成功');
        console.log('JSON 1 内容:', testJson1);
        console.log('JSON 2 内容:', testJson2);

        // 步骤 2: 填充编辑器
        console.log('步骤 2: 填充编辑器内容');
        jsonComparator.editor1.value = testJson1;
        jsonComparator.editor2.value = testJson2;
        console.log('✓ 编辑器内容已填充');

        // 步骤 3: 验证 JSON
        console.log('步骤 3: 验证 JSON 格式');
        const result1 = jsonComparator.validateJSON(1);
        const result2 = jsonComparator.validateJSON(2);

        if (!result1.valid || !result2.valid) {
            throw new Error('测试数据 JSON 格式无效');
        }
        console.log('✓ JSON 格式验证通过');

        // 步骤 4: 更新统计信息
        console.log('步骤 4: 更新统计信息');
        jsonComparator.updateStats();
        console.log('✓ 统计信息已更新');

        // 步骤 5: 执行对比
        console.log('步骤 5: 执行 JSON 对比');
        jsonComparator.autoCompareJSON();

        // 等待渲染完成
        await new Promise(resolve => setTimeout(resolve, 100));

        // 步骤 6: 验证高亮是否应用
        console.log('步骤 6: 验证高亮渲染');
        const overlay1Content = jsonComparator.overlay1.innerHTML;
        const overlay2Content = jsonComparator.overlay2.innerHTML;

        const hasHighlight1 = overlay1Content.includes('diff-');
        const hasHighlight2 = overlay2Content.includes('diff-');

        console.log('Overlay 1 包含高亮类:', hasHighlight1);
        console.log('Overlay 2 包含高亮类:', hasHighlight2);

        if (hasHighlight1 || hasHighlight2) {
            console.log('✓ 高亮已成功应用');

            // 统计高亮类型
            const addedCount = (overlay2Content.match(/diff-added/g) || []).length;
            const removedCount = (overlay1Content.match(/diff-removed/g) || []).length;
            const modifiedCount1 = (overlay1Content.match(/diff-modified/g) || []).length;
            const modifiedCount2 = (overlay2Content.match(/diff-modified/g) || []).length;

            console.log('高亮统计:');
            console.log('  - 新增 (绿色):', addedCount, '行');
            console.log('  - 删除 (红色):', removedCount, '行');
            console.log('  - 修改 (黄色):', Math.max(modifiedCount1, modifiedCount2), '行');

            UIUtils.showToast(`测试成功！发现 ${jsonComparator.currentDiffs.length} 处差异`, 'success', 3000);
        } else {
            console.warn('⚠ 未检测到高亮类，但对比已执行');
            UIUtils.showToast('测试完成，但未检测到高亮显示', 'warning', 3000);
        }

        // 步骤 7: 显示差异摘要
        console.log('步骤 7: 差异摘要');
        console.log('总差异数:', jsonComparator.currentDiffs.length);
        jsonComparator.currentDiffs.forEach((diff, index) => {
            console.log(`  差异 ${index + 1}:`, {
                类型: diff.type,
                路径: diff.path,
                旧值: diff.oldValue,
                新值: diff.newValue
            });
        });

        console.log('=== 测试完成 ===');

    } catch (error) {
        console.error('测试失败:', error);
        UIUtils.showToast(`测试失败: ${error.message}`, 'error', 5000);

        // 如果加载外部文件失败，使用内联数据作为后备
        console.log('使用内联测试数据作为后备...');
        const fallbackJson1 = `{
  "name": "张三",
  "age": 30,
  "city": "北京",
  "hobbies": [
    "读书",
    "游泳"
  ]
}`;

        const fallbackJson2 = `{
  "name": "张三",
  "age": 31,
  "city": "上海",
  "job": "软件工程师",
  "hobbies": [
    "读书",
    "游泳",
    "编程"
  ]
}`;

        jsonComparator.editor1.value = fallbackJson1;
        jsonComparator.editor2.value = fallbackJson2;
        jsonComparator.validateJSON(1);
        jsonComparator.validateJSON(2);
        jsonComparator.updateStats();
        jsonComparator.autoCompareJSON();

        UIUtils.showToast('已使用内联测试数据', 'info', 3000);
    }
}

// 检查样式功能
function checkStyles() {
    console.log('Checking highlight styles...');

    // 检查动态样式是否存在
    const dynamicStyles = document.getElementById('json-comparator-dynamic-styles');
    console.log('Dynamic styles element exists:', !!dynamicStyles);

    if (dynamicStyles) {
        console.log('Dynamic styles content:', dynamicStyles.textContent);
    }

    // 检查计算样式
    if (jsonComparator && jsonComparator.overlay1 && jsonComparator.overlay2) {
        const overlay1Style = window.getComputedStyle(jsonComparator.overlay1);
        const overlay2Style = window.getComputedStyle(jsonComparator.overlay2);

        console.log('Overlay1 style - position:', overlay1Style.position, 'z-index:', overlay1Style.zIndex);
        console.log('Overlay2 style - position:', overlay2Style.position, 'z-index:', overlay2Style.zIndex);
    }

    // 检查CSS规则
    const sheets = document.styleSheets;
    for (let i = 0; i < sheets.length; i++) {
        try {
            const rules = sheets[i].cssRules || sheets[i].rules;
            for (let j = 0; j < rules.length; j++) {
                if (rules[j].selectorText && rules[j].selectorText.includes('diff-')) {
                    console.log('Found highlight CSS rule:', rules[j].selectorText, rules[j].cssText);
                }
            }
        } catch (e) {
            console.log('Cannot access stylesheet:', i, e);
        }
    }
}

// 全面集成测试
async function runIntegrationTests() {
    if (!jsonComparator) {
        console.error('JSONComparator not initialized');
        UIUtils.showToast('测试失败：JSON 对比工具未初始化', 'error');
        return;
    }

    console.log('=== 开始全面集成测试 ===');
    UIUtils.showToast('开始全面集成测试...', 'info', 2000);

    const results = {
        passed: 0,
        failed: 0,
        tests: []
    };

    const runSingleTest = (name, json1, json2, validator) => {
        return new Promise((resolve) => {
            console.log(`\n--- ${name} ---`);
            jsonComparator.editor1.value = json1;
            jsonComparator.editor2.value = json2;
            jsonComparator.autoCompareJSON();

            setTimeout(() => {
                try {
                    const passed = validator();
                    if (passed) {
                        console.log(`✓ ${name} 通过`);
                        results.passed++;
                        results.tests.push({ name, status: 'passed' });
                    } else {
                        console.log(`✗ ${name} 失败`);
                        results.failed++;
                        results.tests.push({ name, status: 'failed' });
                    }
                } catch (error) {
                    console.log(`✗ ${name} 失败:`, error.message);
                    results.failed++;
                    results.tests.push({ name, status: 'failed', error: error.message });
                }
                resolve();
            }, 150);
        });
    };

    // 测试 1: 空 JSON
    await runSingleTest(
        '测试 1: 空 JSON',
        '',
        '',
        () => {
            const summary = jsonComparator.diffSummary.textContent;
            return summary.includes('完全相同');
        }
    );

    // 测试 2: 无效 JSON
    await runSingleTest(
        '测试 2: 无效 JSON',
        '{invalid}',
        '{"valid": true}',
        () => {
            const error1 = jsonComparator.error1.classList.contains('show');
            return error1;
        }
    );

    // 测试 3: 相同 JSON
    await runSingleTest(
        '测试 3: 相同 JSON',
        '{"name": "测试", "age": 30}',
        '{"name": "测试", "age": 30}',
        () => {
            const summary = jsonComparator.diffSummary.textContent;
            return summary.includes('完全相同') && jsonComparator.currentDiffs.length === 0;
        }
    );

    // 测试 4: 复杂嵌套结构（3+ 层）
    await runSingleTest(
        '测试 4: 复杂嵌套结构',
        JSON.stringify({
            user: {
                profile: {
                    personal: {
                        name: "张三",
                        age: 30
                    }
                }
            }
        }, null, 2),
        JSON.stringify({
            user: {
                profile: {
                    personal: {
                        name: "张三",
                        age: 31
                    }
                }
            }
        }, null, 2),
        () => {
            return jsonComparator.currentDiffs.length > 0 &&
                jsonComparator.currentDiffs.some(d => d.path.includes('personal.age'));
        }
    );

    // 测试 5: 特殊字符
    await runSingleTest(
        '测试 5: 特殊字符 (&, <, >, ", \')',
        '{"text": "Hello & <World>"}',
        '{"text": "Hello & <World>", "quote": "\\"test\\""}',
        () => {
            const overlay2 = jsonComparator.overlay2.innerHTML;
            return overlay2.includes('&amp;') && overlay2.includes('&lt;') && overlay2.includes('&gt;');
        }
    );

    // 测试 6: Unicode 字符
    await runSingleTest(
        '测试 6: Unicode 字符（中文、emoji）',
        '{"message": "你好世界", "emoji": "😀"}',
        '{"message": "你好世界", "emoji": "😀", "extra": "🎉"}',
        () => {
            return jsonComparator.currentDiffs.length > 0;
        }
    );

    // 测试 7: 数组差异
    await runSingleTest(
        '测试 7: 数组差异',
        '{"items": [1, 2, 3]}',
        '{"items": [1, 2, 3, 4]}',
        () => {
            return jsonComparator.currentDiffs.some(d => d.path.includes('[3]'));
        }
    );

    // 测试 8: 长 JSON 文件（滚动同步）
    await runSingleTest(
        '测试 8: 长 JSON 文件',
        JSON.stringify({
            items: Array.from({ length: 50 }, (_, i) => ({ id: i, name: `Item ${i}` }))
        }, null, 2),
        JSON.stringify({
            items: Array.from({ length: 50 }, (_, i) => ({ id: i, name: `Item ${i}`, modified: i === 25 }))
        }, null, 2),
        () => {
            // 测试滚动同步
            jsonComparator.editor1.scrollTop = 100;
            jsonComparator.editor1.dispatchEvent(new Event('scroll'));
            setTimeout(() => {
                const syncedScroll = Math.abs(jsonComparator.overlay1.scrollTop - 100) < 5;
                return syncedScroll;
            }, 50);
            return jsonComparator.currentDiffs.length > 0;
        }
    );

    // 测试 9: runTest() 函数
    console.log('\n--- 测试 9: runTest() 函数 ---');
    try {
        await runTest();
        console.log('✓ 测试 9 通过: runTest() 执行成功');
        results.passed++;
        results.tests.push({ name: 'runTest() 函数', status: 'passed' });
    } catch (error) {
        console.log('✗ 测试 9 失败:', error.message);
        results.failed++;
        results.tests.push({ name: 'runTest() 函数', status: 'failed', error: error.message });
    }

    // 测试 10: checkStyles() 函数
    console.log('\n--- 测试 10: checkStyles() 函数 ---');
    try {
        checkStyles();
        console.log('✓ 测试 10 通过: checkStyles() 执行成功');
        results.passed++;
        results.tests.push({ name: 'checkStyles() 函数', status: 'passed' });
    } catch (error) {
        console.log('✗ 测试 10 失败:', error.message);
        results.failed++;
        results.tests.push({ name: 'checkStyles() 函数', status: 'failed', error: error.message });
    }

    // 测试 11: 窗口调整大小
    console.log('\n--- 测试 11: 窗口调整大小 ---');
    try {
        const originalWidth = window.innerWidth;
        window.dispatchEvent(new Event('resize'));
        setTimeout(() => {
            // 检查覆盖层是否仍然对齐
            const overlay1Rect = jsonComparator.overlay1.getBoundingClientRect();
            const editor1Rect = jsonComparator.editor1.getBoundingClientRect();
            const aligned = Math.abs(overlay1Rect.left - editor1Rect.left) < 5;

            if (aligned) {
                console.log('✓ 测试 11 通过: 窗口调整后覆盖层仍然对齐');
                results.passed++;
                results.tests.push({ name: '窗口调整大小', status: 'passed' });
            } else {
                console.log('✗ 测试 11 失败: 窗口调整后覆盖层未对齐');
                results.failed++;
                results.tests.push({ name: '窗口调整大小', status: 'failed' });
            }
        }, 100);
    } catch (error) {
        console.log('✗ 测试 11 失败:', error.message);
        results.failed++;
        results.tests.push({ name: '窗口调整大小', status: 'failed', error: error.message });
    }

    // 等待所有异步测试完成
    await new Promise(resolve => setTimeout(resolve, 500));

    // 显示最终结果
    console.log('\n=== 全面集成测试完成 ===');
    console.log(`总测试数: ${results.passed + results.failed}`);
    console.log(`通过: ${results.passed}`);
    console.log(`失败: ${results.failed}`);
    console.log(`成功率: ${((results.passed / (results.passed + results.failed)) * 100).toFixed(1)}%`);

    console.log('\n详细结果:');
    results.tests.forEach((test, index) => {
        const icon = test.status === 'passed' ? '✓' : '✗';
        const errorMsg = test.error ? ` (${test.error})` : '';
        console.log(`${index + 1}. ${icon} ${test.name}: ${test.status}${errorMsg}`);
    });

    if (results.failed === 0) {
        UIUtils.showToast(`🎉 所有测试通过！(${results.passed}/${results.passed + results.failed})`, 'success', 5000);
    } else {
        UIUtils.showToast(`测试完成: ${results.passed} 通过, ${results.failed} 失败`, 'warning', 5000);
    }
}

// 手动验证测试套件
function runVerificationTests() {
    if (!jsonComparator) {
        console.error('JSONComparator not initialized');
        UIUtils.showToast('验证失败：JSON 对比工具未初始化', 'error');
        return;
    }

    console.log('=== 开始验证测试套件 ===');
    UIUtils.showToast('开始系统验证测试...', 'info', 2000);

    const results = {
        passed: 0,
        failed: 0,
        tests: []
    };

    // 测试 1: 新增属性（绿色高亮，仅在右侧）
    console.log('\n--- 测试 1: 新增属性 ---');
    const test1Json1 = '{"name": "测试"}';
    const test1Json2 = '{"name": "测试", "age": 25}';

    jsonComparator.editor1.value = test1Json1;
    jsonComparator.editor2.value = test1Json2;
    jsonComparator.autoCompareJSON();

    setTimeout(() => {
        const hasGreenInRight = jsonComparator.overlay2.innerHTML.includes('diff-added');
        const noGreenInLeft = !jsonComparator.overlay1.innerHTML.includes('diff-added');

        if (hasGreenInRight && noGreenInLeft) {
            console.log('✓ 测试 1 通过: 新增属性正确显示绿色高亮（仅右侧）');
            results.passed++;
            results.tests.push({ name: '新增属性', status: 'passed' });
        } else {
            console.log('✗ 测试 1 失败: 新增属性高亮不正确');
            results.failed++;
            results.tests.push({ name: '新增属性', status: 'failed' });
        }

        // 测试 2: 删除属性（红色高亮，仅在左侧）
        console.log('\n--- 测试 2: 删除属性 ---');
        const test2Json1 = '{"name": "测试", "age": 25}';
        const test2Json2 = '{"name": "测试"}';

        jsonComparator.editor1.value = test2Json1;
        jsonComparator.editor2.value = test2Json2;
        jsonComparator.autoCompareJSON();

        setTimeout(() => {
            const hasRedInLeft = jsonComparator.overlay1.innerHTML.includes('diff-removed');
            const noRedInRight = !jsonComparator.overlay2.innerHTML.includes('diff-removed');

            if (hasRedInLeft && noRedInRight) {
                console.log('✓ 测试 2 通过: 删除属性正确显示红色高亮（仅左侧）');
                results.passed++;
                results.tests.push({ name: '删除属性', status: 'passed' });
            } else {
                console.log('✗ 测试 2 失败: 删除属性高亮不正确');
                results.failed++;
                results.tests.push({ name: '删除属性', status: 'failed' });
            }

            // 测试 3: 修改属性（黄色高亮，两侧都有）
            console.log('\n--- 测试 3: 修改属性 ---');
            const test3Json1 = '{"name": "张三", "age": 30}';
            const test3Json2 = '{"name": "张三", "age": 31}';

            jsonComparator.editor1.value = test3Json1;
            jsonComparator.editor2.value = test3Json2;
            jsonComparator.autoCompareJSON();

            setTimeout(() => {
                const hasYellowInLeft = jsonComparator.overlay1.innerHTML.includes('diff-modified');
                const hasYellowInRight = jsonComparator.overlay2.innerHTML.includes('diff-modified');

                if (hasYellowInLeft && hasYellowInRight) {
                    console.log('✓ 测试 3 通过: 修改属性正确显示黄色高亮（两侧）');
                    results.passed++;
                    results.tests.push({ name: '修改属性', status: 'passed' });
                } else {
                    console.log('✗ 测试 3 失败: 修改属性高亮不正确');
                    results.failed++;
                    results.tests.push({ name: '修改属性', status: 'failed' });
                }

                // 测试 4: 验证颜色值
                console.log('\n--- 测试 4: 验证颜色值 ---');
                const addedElements = jsonComparator.overlay2.querySelectorAll('.diff-added');
                const removedElements = jsonComparator.overlay1.querySelectorAll('.diff-removed');
                const modifiedElements = jsonComparator.overlay1.querySelectorAll('.diff-modified');

                let colorTestPassed = true;

                // 检查绿色（新增）
                if (addedElements.length > 0) {
                    const addedStyle = window.getComputedStyle(addedElements[0]);
                    const bgColor = addedStyle.backgroundColor;
                    console.log('新增元素背景色:', bgColor);
                    // RGB(212, 237, 218) = #d4edda
                    if (!bgColor.includes('212') && !bgColor.includes('237')) {
                        colorTestPassed = false;
                        console.log('✗ 新增元素颜色不正确');
                    }
                }

                // 检查红色（删除）
                if (removedElements.length > 0) {
                    const removedStyle = window.getComputedStyle(removedElements[0]);
                    const bgColor = removedStyle.backgroundColor;
                    console.log('删除元素背景色:', bgColor);
                    // RGB(248, 215, 218) = #f8d7da
                    if (!bgColor.includes('248') && !bgColor.includes('215')) {
                        colorTestPassed = false;
                        console.log('✗ 删除元素颜色不正确');
                    }
                }

                // 检查黄色（修改）
                if (modifiedElements.length > 0) {
                    const modifiedStyle = window.getComputedStyle(modifiedElements[0]);
                    const bgColor = modifiedStyle.backgroundColor;
                    console.log('修改元素背景色:', bgColor);
                    // RGB(255, 243, 205) = #a59e86ff
                    if (!bgColor.includes('255') && !bgColor.includes('243')) {
                        colorTestPassed = false;
                        console.log('✗ 修改元素颜色不正确');
                    }
                }

                if (colorTestPassed) {
                    console.log('✓ 测试 4 通过: 颜色值正确');
                    results.passed++;
                    results.tests.push({ name: '颜色值验证', status: 'passed' });
                } else {
                    console.log('✗ 测试 4 失败: 颜色值不正确');
                    results.failed++;
                    results.tests.push({ name: '颜色值验证', status: 'failed' });
                }

                // 显示最终结果
                console.log('\n=== 验证测试完成 ===');
                console.log(`通过: ${results.passed} / ${results.passed + results.failed}`);
                console.log(`失败: ${results.failed} / ${results.passed + results.failed}`);

                results.tests.forEach(test => {
                    const icon = test.status === 'passed' ? '✓' : '✗';
                    console.log(`${icon} ${test.name}: ${test.status}`);
                });

                if (results.failed === 0) {
                    UIUtils.showToast(`所有测试通过！(${results.passed}/${results.passed})`, 'success', 5000);
                } else {
                    UIUtils.showToast(`测试完成: ${results.passed} 通过, ${results.failed} 失败`, 'warning', 5000);
                }

            }, 200);
        }, 200);
    }, 200);
}
